package com.cw.jeeyt.controller.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cw.jeeyt.service.bo.system.SystemDictCacheBo;
import com.cw.jeeyt.api.dto.response.JsonResultDto;
import com.cw.jeeyt.common.Constants;
import com.cw.jeeyt.common.DataTable;
import com.cw.jeeyt.common.ResultData;
import com.cw.jeeyt.common.enums.EnumOperateFlag;
import com.cw.jeeyt.common.web.BaseController;
import com.cw.jeeyt.service.bo.system.SystemDictBo;
import com.cw.jeeyt.service.bo.system.SystemModuleInfoBo;
import com.cw.jeeyt.service.bo.system.SystemProjectInfoBo;
import com.cw.jeeyt.service.directive.PageDictDirective;
import com.cw.jeeyt.service.directive.PermissionDirective;
import com.cw.jeeyt.service.intf.system.SystemDictService;
import com.cw.jeeyt.service.intf.system.SystemModuleInfoService;
import com.cw.jeeyt.service.intf.system.SystemProjectInfoService;
import com.cw.jeeyt.service.utils.DataDicUtils;
import com.cw.jeeyt.service.utils.DictUtils;
import com.cw.lang.common.utils.CollectionUtil;
import com.cw.lang.mybatis.dto.PageInfo;

/**
 * 数据字典控制类
 * @author chenw
* @version 1.0.0
 */
@Controller
@RequestMapping("/systemDict")
public class SystemDictController extends BaseController {
    @Resource
    private SystemDictService systemDictService;
    @Autowired
    private SystemModuleInfoService systemModuleInfoService;
    @Autowired
    private SystemProjectInfoService systemProjectInfoService;
    /**
     * 跳转到列表查询页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/query")
    public ModelAndView query() throws Exception {
        ModelAndView mv = new ModelAndView("system/systemDict_index");
        mv.addObject("permission", new PermissionDirective());
        return mv;
    }

    /**
     * 加载DataTable列表数据
     *
     * @param dataTable 请求数据
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/listSystemDict")
    public ResultData listSystemDict(@RequestBody DataTable dataTable) throws Exception {

        SystemDictBo systemDictBo = JSONObject.parseObject(JSON.toJSONString(dataTable.getQueryCond()),
            SystemDictBo.class);
        if (systemDictBo == null) {
            systemDictBo = new SystemDictBo();
        }
        PageInfo<SystemDictCacheBo> pageInfo = systemDictService.queryByPage(systemDictBo, dataTable.getStart(),
            dataTable.getLength());
        return ResultData.builder()
            .draw(dataTable.getDraw())
            .data(CollectionUtil.isNotEmpty(pageInfo.getList())?pageInfo.getList():new ArrayList())
            .recordsTotal(pageInfo.getTotal())
            .recordsFiltered(pageInfo.getTotal())
            .build();
    }

    /**
     * 跳转到表单页面
     *
     * @param id 主键
     * @param operation 操作  add 新增 edit修改 view查看
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/to-form")
    public ModelAndView toForm(String id, String operation) throws Exception {
        ModelAndView mv = new ModelAndView("system/systemDict_form");
        SystemDictBo systemDictBo;
        List<SystemDictCacheBo> itemDictList = new ArrayList<>();
        if (EnumOperateFlag.ADD.getCode()
            .equals(operation)) {
            systemDictBo = new SystemDictBo();
        } else {
            systemDictBo = systemDictService.getSystemDictById(id);
            itemDictList = systemDictService.getItemDictListByParentId(id);
        }
        mv.addObject("systemDict", systemDictBo);
        mv.addObject("itemDictList", itemDictList);
        mv.addObject("operation", operation);
        mv.addObject("PageDict", new PageDictDirective());
        return mv;
    }

    /**
     * 跳转到子项表单页面
     *
     * @param id 主键
     * @param operation 操作  add 新增 edit修改 view查看
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/to-itemForm")
    public ModelAndView toForm(String id, String parentId, String operation)
    throws Exception {
        ModelAndView mv = new ModelAndView("system/systemDict_itemForm");
        SystemDictBo systemDictBo = null;
        if (EnumOperateFlag.ADD.getCode()
            .equals(operation)) {
            systemDictBo = new SystemDictBo();
            systemDictBo.setParentId(parentId);
        } else {
            systemDictBo = systemDictService.getSystemDictById(id);
        }
        mv.addObject("systemDict", systemDictBo);
        mv.addObject("operation", operation);
        mv.addObject("permission", new PermissionDirective());
        return mv;
    }

    /**
     * 根据操作类型保存数据
     *
     * @param systemDictBo
     * @param operation add新增  edit修改 view查看
     */
    @ResponseBody
    @RequestMapping(value = "/saveSystemDict", method = RequestMethod.POST)
    public JsonResultDto saveSystemDict(SystemDictBo systemDictBo, String operation) {

        String id = "";
        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            if (operation.equals(EnumOperateFlag.ADD.getCode())) {
                id = systemDictService.insertSystemDict(systemDictBo);
            } else if (operation.equals(EnumOperateFlag.EDIT.getCode())) {
                systemDictService.updateSystemDict(systemDictBo);
                id = systemDictBo.getId();
            }
            jsonResultDto.setMsg("保存成功");
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("保存失败:" + e.getMessage());

        }
        jsonResultDto.setOperation(operation);
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        jsonResultDto.setResultData(map);
        return jsonResultDto;
    }

    /**
     * 删除数据字典
     *
     * @param systemDictBo
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public JsonResultDto deleteSystemDict(SystemDictBo systemDictBo) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            systemDictService.deleteSystemDict(systemDictBo);
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();

            jsonResultDto.setMsg("删除失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 查询数据字典信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/initDict")
    public JsonResultDto queryPubDict(String dictStr) {

        JSONArray jsonArray = null;
        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            if (StringUtils.isNotEmpty(dictStr)) {
                jsonArray = JSON.parseArray(dictStr);
            }
            if (jsonArray != null && !jsonArray.isEmpty()) {
                List<Map<String, Object>> resultDict = DataDicUtils.getDataDicItem(jsonArray);
                Map<String, Object> map = new HashMap<>();
                map.put("dictList", JSON.toJSONString(resultDict));
                jsonResultDto.setResultData(map);
            }
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("数据字典加载失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 查询数据字典信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkDictCode")
    public JsonResultDto checkDictCode(String dictCode,String moduleId) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            Map<String, Object> map = new HashMap<>();
            //如果不是本工程生成代码，则跳过校验
            SystemModuleInfoBo systemModuleInfoBo = systemModuleInfoService.getSystemModuleInfoById(moduleId);
            if(systemModuleInfoBo != null){
                SystemProjectInfoBo systemProjectInfoBo = systemProjectInfoService.getSystemProjectInfoById(systemModuleInfoBo.getProjectId());
                if(!Constants.PROJECT_CODE.equals(systemProjectInfoBo.getProjectCode())){
                    jsonResultDto.setSuccess(true);
                    map.put("isExist", true);
                    jsonResultDto.setResultData(map);
                    return jsonResultDto;
                }
            }
            SystemDictCacheBo systemDictBo = systemDictService.getSystemDictByItemCode(dictCode);
            if (systemDictBo != null) {
                map.put("isExist", true);
            } else {
                jsonResultDto.setMsg("数据字典编码不存在，请重新输入");
                map.put("isExist", false);
            }
            jsonResultDto.setResultData(map);
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();

            jsonResultDto.setMsg(e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 查询数据字典信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/loadDictInfo")
    public JsonResultDto loadDictInfo(String itemCode, String itemName, String itemValue) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("dictInfo", DictUtils.getDict(itemCode, itemName, itemValue));
            jsonResultDto.setResultData(map);
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();

            jsonResultDto.setMsg(e.getMessage());
        }
        return jsonResultDto;
    }
}
